package com.atguigu.servicemsm.controller;

import com.atguigu.commonutils.R;
import com.atguigu.commonutils.RandomUtil;
import com.atguigu.servicemsm.service.MsmService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author JY
 * @create 2021-01-28 23:20
 */
@RestController
@RequestMapping("/msm")
//@CrossOrigin
public class MsmController {
    @Autowired
    private MsmService msmService;

    //添加缓存逻辑
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @GetMapping("send/{phone}")
    public R send(@PathVariable String phone){
        //先判断redis中是否有验证码
        String code = redisTemplate.opsForValue().get(phone);
        if(!StringUtils.isEmpty(code)){
            return R.ok();
        }
        //生成随机验证码
        code = RandomUtil.getFourBitRandom();
        System.out.println("验证码为:"+code);
        //由于后面阿里云上传参数要传json格式，这里给他封装成Map
//        Map<String,Object> param = new HashMap<>();
//        param.put("code",code);
//        boolean isSend = msmService.send(phone,param);
        boolean isSend = true;
        if(isSend){
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);//验证码在redis存留5分钟
            return R.ok();
        }
        return R.error().message("发送短信失败");
    }
}
